from django.shortcuts import render, redirect

# Create your views here.

# 前端
from django.http import HttpResponse

# 模型（db数据表）
from .models import Room, Topic, Message, User, IP

# 表单
from .forms import RoomForm, UserForm, MyUserCreationForm

# 条件过滤
from django.db.models import Q

# flash 消息框架
from django.contrib import messages

# 身份认证
from django.contrib.auth import authenticate, login, logout

# 装饰器 限制视图
from django.contrib.auth.decorators import login_required

# 检查是否为房间成员 # 简单响应
from django.http import HttpResponse

# 新建用户表单
from django.contrib.auth.forms import UserCreationForm


# rooms = [
#     {'id': 1, 'name': '让我们学习 python !'},
#     {'id': 2, 'name': '来玩 CSGO !'},
#     {'id': 3, 'name': '讨论 nyist university !'},
# ]
# def login_page(request):
#     page = 'login'  # 用于标识 # login 和 register 共用一张 login_register.html
#
#     if request.user.is_authenticated:  # 禁止已登录用户通过url重复登录
#         return redirect('home')
#
#     if request.method == 'POST':
#         email = request.POST.get('email').lower()
#         password = request.POST.get('password')
#
#         #  判断用户是否存在
#         try:
#             User.objects.get(email=email)
#         except:
#             messages.error(request, '用户不存在 ！')
#             return redirect('login')
#
#         #  验证用户
#         user = authenticate(request, email=email, password=password)
#
#         if user is not None:
#             login(request, user)
#             return redirect('home')
#         else:
#             messages.error(request, '用户或密码输入错误 ！')
#
#     content = {'page': page}
#     return render(request, 'base/login_register.html', content)
#


def login_page(request):
    page = 'login'  # 用于标识 # login 和 register 共用一张 login_register.html

    if request.user.is_authenticated:  # 禁止已登录用户通过url重复登录
        return redirect('home')

    if request.method == 'POST':
        username = request.POST.get('username').lower()
        password = request.POST.get('password')

        #  判断用户是否存在
        try:
            User.objects.get(username=username)
        except:
            messages.error(request, '用户不存在 ！')
            return redirect('login')

        #  验证用户
        user = authenticate(request,username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('home')
        else:
            messages.error(request, '用户或密码输入错误 ！')

    content = {'page': page}
    return render(request, 'base/login_register.html', content)



def register_page(request):
    form = MyUserCreationForm()
    content = {'form': form}

    if request.method == 'POST':
        form = MyUserCreationForm(request.POST)
        print(form)
        if form.is_valid():
            user = form.save(commit=False)  # 不保存数据 # 生成一个user的实例对象
            user.username = user.username.lower()
            user.save()
            login(request, user)
            return redirect('home')
        else:
            messages.error(request, '注册错误')

    return render(request, 'base/login_register.html', content)




def logout_user(request):
    logout(request)
    return redirect('home')


def home(request):
    # 记录访问者 ip
    if request.META.get('HTTP_X_FORWARDED_FOR'):
        ip = request.META.get("HTTP_X_FORWARDED_FOR")
    else:
        ip = request.META.get("REMOTE_ADDR")

    if request.user.is_authenticated:
        user = request.user
        IP.objects.create(ip=ip, user=user)
    else:
        IP.objects.create(ip=ip)



    if request.GET.get('q') is None:
        q = ''
    else:
        q = request.GET.get('q')

    rooms = Room.objects.filter(Q(topic__name__icontains=q) |  # 过滤器 过滤相关主题topic的 房间room
                                Q(name__icontains=q) |
                                Q(desc__icontains=q)
                                )

    topics = Topic.objects.all()[0: 6]  # 默认仅展示前6个主题
    room_count = rooms.count()
    # 最近活跃
    room_messages = Message.objects.filter(Q(room__topic__name__icontains=q),  # 过滤器 过滤相关主题的房间room 的消息message

                                           ).order_by('-id')[:6]

    context = {'rooms': rooms, 'topics': topics, 'room_count': room_count, 'room_messages': room_messages}
    return render(request, 'base/home.html', context)


def room(request, pk):
    room_pk = Room.objects.get(id=pk)
    # 最新评论靠前
    room_message = room_pk.message_set.all().order_by('-created')
    # 参与者
    participants = room_pk.participants.all()
    # 接收发来的消息 # 在模型中穿件它的对象 即保存到数据库
    if request.method == "POST":
        if request.user.is_authenticated:
            message = Message.objects.create(
                user=request.user,
                room=room_pk,
                body=request.POST.get('body')
            )
            # 发送者被添加到房间的 participants属性中
            room_pk.participants.add(request.user)
            return redirect('room', pk=room_pk.id)
        else:
            return redirect('login')

    context = {'room_pk': room_pk, 'room_message': room_message, 'participants': participants}
    return render(request, 'base/room.html', context)


@login_required(login_url='/login')  # 装饰器 #验证是否登录 否则重定向到login
def create_room(request):
    form = RoomForm()
    topics = Topic.objects.all()  # 前端制作选项卡

    if request.method == 'POST':
        # 创建房间 判断重复
        topic_name = request.POST.get('topic')
        topic, created = Topic.objects.get_or_create(name=topic_name)  # 不存在则创建

        Room.objects.create(
            host=request.user,
            topic=topic,
            name=request.POST.get('name'),
            desc=request.POST.get('desc')
        )
        topic.room_count += 1  # 计数
        return redirect('home')  # 参数为urls.py 某条路径的name属性

    context = {'form': form, 'topics': topics}
    return render(request, 'base/room_form.html', context)


@login_required(login_url='/login')  # 装饰器 #验证是否登录 否则重定向到login
def update_room(request, pk):
    room_pk = Room.objects.get(id=pk)
    form = RoomForm(instance=room_pk)  # 用room_pk数据初始化RoomForm表单
    topics = Topic.objects.all()

    # 检查请求是否来自房间主人host
    if request.user != room_pk.host:
        return HttpResponse('你不是该学习室创建者，没有编辑权限 !')

    if request.method == 'POST':
        # 更新房间
        topic_name = request.POST.get('topic')
        topic, created = Topic.objects.get_or_create(name=topic_name)  # 不存在则创建
        # 计数
        if topic.name != request.POST.topic:
            topic.room_count += 1
            room_pk.topic.room_count -= 1

        room_pk.name = request.POST.get('name')
        room_pk.topic = topic
        room_pk.desc = request.POST.get('desc')
        room_pk.save()
        return redirect('home')  # 参数为urls.py 某条路径的name属性

    context = {'form': form, 'topics': topics, 'room_pk': room_pk}
    return render(request, 'base/room_form.html', context)


@login_required(login_url='/login')  # 装饰器 #验证是否登录 否则重定向到login
def delete_room(request, pk):
    room_pk = Room.objects.get(id=pk)

    # 检查请求是否来自房间主人host
    if request.user != room_pk.host:
        return HttpResponse('你不是该学习室房主，没有编辑权限 !')

    if request.method == 'POST':
        room_pk.delete()

        topic = room_pk.topic
        topic.room_count -= 1  # 计数
        return redirect("home")
    return render(request, 'base/delete.html', {'obj': room_pk})


@login_required(login_url='/login')  # 装饰器 #验证是否登录 否则重定向到login
def delete_message(request, pk):
    msg_pk = Message.objects.get(id=pk)

    # 检查请求是否来自房间主人host 或发送消息的人user
    if request.user not in (msg_pk.user, msg_pk.room.host):
        return HttpResponse('你不是该房间主人 或发消息者，没有删除权限 !')

    if request.method == 'POST':
        msg_pk.delete()
        # return redirect(request.META.HTTP_REFERER)
        return redirect("home")
    return render(request, 'base/delete.html', {'obj': msg_pk})


def user_profile(request, pk):
    user_pk = User.objects.get(id=pk)
    rooms = user_pk.room_set.all()
    room_messages = user_pk.message_set.all()
    topics = Topic.objects.all()[0:5]

    content = {'user_pk': user_pk, 'rooms': rooms, 'room_messages': room_messages, 'topics': topics}

    return render(request, 'base/profile.html', content)


@login_required(login_url='/login')
def update_user(request):
    user = request.user
    form = UserForm(instance=user)

    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES, instance=user)
        if form.is_valid():
            form.save()
            return redirect('user-profile', pk=user.id)

    content = {'form': form}
    return render(request, 'base/update_user.html', content)


def mb_topics_page(request):  # mobile 移动端主题Topics视图
    if request.GET.get('q') is not None:
        q = request.GET.get('q')
        topics = Topic.objects.filter(name__icontains=q)
    else:
        topics = Topic.objects.all()[0:6]

    content = {'topics': topics}
    return render(request, 'base/mb_topics.html', content)


def mb_activity_page(request):  # mobile 移动端主题Activity视图

    room_messages = Message.objects.all()

    content = {'room_messages': room_messages}
    return render(request, 'base/mb_activity.html', content)
